package com.originskyseed.platform.recruit.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.filter.helper.SingleSignOnTokenHelper;
import com.originskyseed.platform.recruit.i18n.RecruitResponseMsg;
import com.originskyseed.platform.recruit.model.RankingListVO;
import com.originskyseed.platform.recruit.model.Recruit;
import com.originskyseed.platform.recruit.service.IRecruitService;
import com.originskyseed.platform.recruit.vo.request.RankingRequestVO;
import com.originskyseed.platform.recruit.vo.request.RecruitRequestVO;
import com.originskyseed.platform.user.model.Dept;
import com.originskyseed.platform.user.model.UserInfo;
import com.originskyseed.platform.user.service.IDeptService;

/**
 * 招聘信息表Controller类（OSI_RECRUIT）
 *
 * @author Tangwanghui
 */
@Controller
@RequestMapping("/recruit")
@BaseLocaleResource(localeFileName = "i18n_recruit")
public class RecruitController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(RecruitController.class);

	@DubboReference
	private IRecruitService recruitService;

	@DubboReference
	private IDeptService deptService;

	/**
	 * 分页查询
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/recruitList.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<Recruit>> recruitList(HttpServletRequest request) {
		BaseResponseBody<BasePage<Recruit>> result = null;
		try {
			// 请求对象
			RecruitRequestVO requestVO = this.getParameterBean(RecruitRequestVO.class);

			// 分页查询
			BasePage<Recruit> page = new BasePage<Recruit>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.recruitService.selectListByPage(requestVO.toMap(), page);
			result = new BaseResponseBody<BasePage<Recruit>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), RecruitResponseMsg.DATA_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<Recruit>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RecruitResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 保存信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/recruitSave.json", method = RequestMethod.POST)
	public BaseResponseBody<Recruit> recruitSave(HttpServletRequest request) {
		BaseResponseBody<Recruit> result = null;
		try {
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			// 请求对象
			Recruit recruit = this.getParameterBean(Recruit.class);
			if (StringUtils.isNotBlank(recruit.getBelongDeptId())) {
				Dept dept = deptService.selectByPrimaryKey(recruit.getBelongDeptId());
				if (dept != null) {
					recruit.setBelongDeptName(dept.getName());
				}
			}

			if (StringUtils.isNotBlank(recruit.getId())) {
				this.recruitService.updateByPrimaryKeySelective(recruit);
			} else {
				recruit.setState(1);
				recruit.setCreatorId(userInfo.getId());
				recruit.setCreator(userInfo.getName());
				this.recruitService.insertSelective(recruit);
			}
			result = new BaseResponseBody<Recruit>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), RecruitResponseMsg.DATA_SAVE_SUCCESS.getMsg()), recruit);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Recruit>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RecruitResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 删除信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/recruitDelete.json", method = RequestMethod.POST)
	@RequiredParams(names = { "ids" })
	public BaseResponseBody<Boolean> recruitDelete(HttpServletRequest request) {
		BaseResponseBody<Boolean> result = null;
		try {
			// 请求参数
			String[] ids = this.getParameterArray("ids", new String[] {});

			this.recruitService.deleteByPrimaryKeys(Arrays.asList(ids));
			result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), RecruitResponseMsg.DATA_DELETE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RecruitResponseMsg.DATA_DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 批量修改状态
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateRecruitStatus.json", method = RequestMethod.POST)
	@RequiredParams(names = { "ids", "state" })
	public BaseResponseBody<Boolean> updateCourseStatus(HttpServletRequest request) {
		BaseResponseBody<Boolean> result = null;
		try {
			// 请求参数
			String[] ids = this.getParameterArray("ids", new String[] {});
			Integer state = this.getParameterInteger("state", null);

			Map<String, Object> map = new HashMap<>();
			map.put("list", Arrays.asList(ids));
			map.put("state", state);

			this.recruitService.updateStatusByIds(map);
			result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), RecruitResponseMsg.DATA_SAVE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RecruitResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 查询详情
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectRecruitById.json", method = RequestMethod.POST)
	@RequiredParams(names = { "id" })
	public BaseResponseBody selectRecruitById(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数
			String id = this.getParameterString("id", null);

			Recruit recruit = this.recruitService.selectByPrimaryKey(id);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), RecruitResponseMsg.DATA_DELETE_SUCCESS.getMsg()), recruit);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RecruitResponseMsg.DATA_DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 查询列表
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectRecruitList.json", method = RequestMethod.POST)
	public BaseResponseBody selectRecruitList(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			Recruit recruit = this.getParameterBean(Recruit.class);

			// 列表查询
			List<Recruit> recruitList = this.recruitService.selectList(recruit);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), RecruitResponseMsg.DATA_LIST_SUCCESS.getMsg()), recruitList);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RecruitResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 查询榜单
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectRankingList.json", method = RequestMethod.POST)
	@RequiredParams(names = { "size" })
	public BaseResponseBody selectRankingList(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {

			Map<String, Object> map = new HashMap<>();
			// 请求参数
			Integer size = this.getParameterInteger("size", null);
			Integer type = this.getParameterInteger("type", null);
			if (type != null) {
				// 月
				if (type == 0) {
					map.put("startTime", getCurrentMonthStartTime());
					map.put("endTime", getCurrentMonthEndTime());
					// 季
				} else if (type == 1) {
					map.put("startTime", getCurrentQuarterStartTime());
					map.put("endTime", getCurrentQuarterEndTime());
					// 年
				} else if (type == 2) {
					map.put("startTime", getCurrentYearStartTime());
					map.put("endTime", getCurrentYearEndTime());
				}
			}
			map.put("size", size);
			List<RankingListVO> list = this.recruitService.selectRankingList(map);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), RecruitResponseMsg.DATA_LIST_SUCCESS.getMsg()), list);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RecruitResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 查询榜单
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectRankingListByPage.json", method = RequestMethod.POST)
	public BaseResponseBody selectRankingListByPage(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数
			RankingRequestVO requestVO = this.getParameterBean(RankingRequestVO.class);
			Integer type = this.getParameterInteger("type", null);
			if (type != null) {
				// 月
				if (type == 0) {
					requestVO.setStartTime(getCurrentMonthStartTime());
					requestVO.setEndTime(getCurrentMonthEndTime());
					// 季
				} else if (type == 1) {
					requestVO.setStartTime(getCurrentQuarterStartTime());
					requestVO.setEndTime(getCurrentQuarterEndTime());
					// 年
				} else if (type == 2) {
					requestVO.setStartTime(getCurrentYearStartTime());
					requestVO.setEndTime(getCurrentYearEndTime());
				}
			}
			// 分页查询
			BasePage<RankingListVO> page = new BasePage<RankingListVO>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.recruitService.selectRankingListByPage(requestVO.toMap(), page);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), RecruitResponseMsg.DATA_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RecruitResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 查询推荐人数
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectRecommendCount.json", method = RequestMethod.POST)
	public BaseResponseBody selectRecommendCount(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 当前登录用户
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			// 请求参数
			Integer type = this.getParameterInteger("type", null);
			Map<String, Object> query = new HashMap();
			query.put("userId", userInfo.getId());
			if (type != null) {
				// 月
				if (type == 0) {
					query.put("startTime", getCurrentMonthStartTime());
					query.put("endTime", getCurrentMonthEndTime());
					// 季
				} else if (type == 1) {
					query.put("startTime", getCurrentQuarterStartTime());
					query.put("endTime", getCurrentQuarterEndTime());
					// 年
				} else if (type == 2) {
					query.put("startTime", getCurrentYearStartTime());
					query.put("endTime", getCurrentYearEndTime());
				}
			}

			Integer count = this.recruitService.selectRecommendCount(query);
			Integer rank = this.recruitService.selectRankingByCount(query);
			BigDecimal amount = this.recruitService.selectRecommendAmount(query);
			Map<String, Object> map = new HashMap<>();
			map.put("count", count);
			map.put("amount",amount);
			map.put("name", userInfo.getName());
			map.put("headPortrait", userInfo.getHeadPortrait());
			map.put("rank", rank);

			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), RecruitResponseMsg.DATA_LIST_SUCCESS.getMsg()), map);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RecruitResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	// 日期格式化
	private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

	/**
	 * 获得本月的开始时间
	 *
	 * @return
	 */
	public String getCurrentMonthStartTime() {
		Calendar c = Calendar.getInstance();
		try {
			c.set(Calendar.DATE, 1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sdf.format(c.getTime());
	}

	/**
	 * 本月的结束时间
	 *
	 * @return
	 */
	public String getCurrentMonthEndTime() {
		Calendar c = Calendar.getInstance();
		try {
			c.set(Calendar.DATE, 1);
			c.add(Calendar.MONTH, 1);
			c.add(Calendar.DATE, -1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sdf.format(c.getTime());
	}

	/**
	 * 当前季度的开始时间
	 *
	 * @return
	 */
	public String getCurrentQuarterStartTime() {
		Calendar c = Calendar.getInstance();
		int currentMonth = c.get(Calendar.MONTH) + 1;
		try {
			if (currentMonth >= 1 && currentMonth <= 3)
				c.set(Calendar.MONTH, 0);
			else if (currentMonth >= 4 && currentMonth <= 6)
				c.set(Calendar.MONTH, 3);
			else if (currentMonth >= 7 && currentMonth <= 9)
				c.set(Calendar.MONTH, 4);
			else if (currentMonth >= 10 && currentMonth <= 12)
				c.set(Calendar.MONTH, 9);
			c.set(Calendar.DATE, 1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sdf.format(c.getTime());
	}

	/**
	 * 当前季度的结束时间
	 *
	 * @return
	 */
	public String getCurrentQuarterEndTime() {
		Calendar c = Calendar.getInstance();
		int currentMonth = c.get(Calendar.MONTH) + 1;
		try {
			if (currentMonth >= 1 && currentMonth <= 3) {
				c.set(Calendar.MONTH, 2);
				c.set(Calendar.DATE, 31);
			} else if (currentMonth >= 4 && currentMonth <= 6) {
				c.set(Calendar.MONTH, 5);
				c.set(Calendar.DATE, 30);
			} else if (currentMonth >= 7 && currentMonth <= 9) {
				c.set(Calendar.MONTH, 8);
				c.set(Calendar.DATE, 30);
			} else if (currentMonth >= 10 && currentMonth <= 12) {
				c.set(Calendar.MONTH, 11);
				c.set(Calendar.DATE, 31);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sdf.format(c.getTime());
	}

	/**
	 * 当前年的开始时间
	 *
	 * @return
	 */
	public String getCurrentYearStartTime() {
		Calendar c = Calendar.getInstance();
		try {
			c.set(Calendar.MONTH, 0);
			c.set(Calendar.DATE, 1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sdf.format(c.getTime());
	}

	/**
	 * 当前年的结束时间
	 *
	 * @return
	 */
	public String getCurrentYearEndTime() {
		Calendar c = Calendar.getInstance();
		try {
			c.set(Calendar.MONTH, 11);
			c.set(Calendar.DATE, 31);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sdf.format(c.getTime());
	}
}
